package leesoft.configuration.core;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;


import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.QueryRunner;

public class DBToolKit {
	Connection conn=null;
	String driver,connstring,username,password,codepage;
	
	public DBToolKit(String driver,String connstring,String username,String password,String cp){
		this.connstring=connstring;
		this.username=username;
		this.driver=driver;
		this.password=password;
		this.codepage=cp;
		
	}
	
	public void open(){
		DbUtils.loadDriver(driver);
		try{
			conn=DriverManager.getConnection(connstring, username, password);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	public void close(){
		if(conn!=null){
			DbUtils.closeQuietly(conn);
		}
	}
	public void executeOn(String sql_file,int batchSize,Writer out) throws IOException{
		FileReader fr = new FileReader(sql_file);
		BufferedReader br = new BufferedReader(fr);
		StringBuffer sb=new StringBuffer();
		int count=0;
		int linecount=0;
		while(br.ready()){
			sb.append(br.readLine().trim());
			count++;
			linecount++;
			if(count>=batchSize){
				if(flushSql(sb.toString())==false){
					out.write(sb.toString().replaceAll(";", ";\n"));
					out.flush();
				}
				System.out.print("...."+linecount+"....");
				count=0;
				sb=new StringBuffer();
			}
		}
		if(sb.length()>0){
			if(flushSql(sb.toString())==false){
				out.write(sb.toString().replaceAll(";", ";\n"));
				out.flush();
			}
			System.out.print("...."+linecount+"....");
		}
		System.out.println("done");
		br.close();
		fr.close();
	}
	private boolean flushSql(String sql){
		
		try{
			QueryRunner run=new QueryRunner();
			open();
			int ret=run.update(conn,TextConvert.charConvert(sql,this.codepage));
			if(ret!=1){
				System.out.print("...failed...");
				return false;
			}
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}finally{
			close();
		}
		
		
	}
}
